import uuid
import os
import json
import urllib.request

import faster_whisper
from django.conf import settings
from django.http import HttpResponse
import time

from django.views.decorators.csrf import csrf_exempt


class RequestModel:
    def __init__(self, request_url, model_size, file_prefix):
        self.request_url = request_url
        self.model_size = model_size
        self.file_prefix = file_prefix


@csrf_exempt
def hello(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        request_model = RequestModel(data.get('request_url'), data.get('model_size'), data.get('file_prefix'))  #
        print("request.body:", request_model.request_url)
    else:
        return HttpResponse("Hello, world. You're at the polls index.")
    trans_url = request_model.request_url
    # 创建一个本地文件名，文件后缀为使用对应的后缀
    local_filename = f"{str(uuid.uuid4())}.{request_model.file_prefix}"
    use_path = os.path.join(settings.MEDIA_ROOT, local_filename)
    # 下载文件到本地
    urllib.request.urlretrieve(trans_url, use_path)
    # 生成一个UUID
    generated_uuid = str(uuid.uuid4())
    # output_file_path = os.path.join(base_output_path, f"{generated_uuid}.txt")

    output_file_path = os.path.join(settings.MEDIA_ROOT, f"{generated_uuid}.txt")
    # os.makedirs(output_file_path, exist_ok=True)
    start_time = time.time()

    # Initialize and run the model as before
    model = faster_whisper.WhisperModel(model_size_or_path=f"/opt/model/faster-whisper-{request_model.model_size}",
                                        device="cuda", compute_type="float16",
                                        local_files_only=True)
    # 传入数据进行解析
    segments, info = model.transcribe(use_path, beam_size=5, language="zh",
                                      vad_filter=True,
                                      vad_parameters=dict(min_silence_duration_ms=1000))

    # segments, info = model.transcribe("/Users/admin/Downloads/英文音频.mp3", beam_size=5, language="zh",
    #                                   vad_filter=True,
    #                                   vad_parameters=dict(min_silence_duration_ms=1000))

    print("Detected language '%s' with probability %f" % (info.language, info.language_probability))

    # Open the output file in write mode ('w')
    with open(output_file_path, 'w', encoding='utf-8') as file:
        # Write the detected language information
        file.write(f"Detected language: {info.language} (Probability: {info.language_probability})\n\n")

        # Write each segment's text to the file
        for segment in segments:
            file.write(f"[{segment.start:.2f}s -> {segment.end:.2f}s]: {segment.text}\n")

    end_time = time.time()
    total_time = end_time - start_time
    print(f"Total execution time: {total_time:.6f} seconds")

    return HttpResponse(data)
